#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <errno.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

void process_log(const char *log_path) {
    // 调用之前实现的 audit-seal 进行日志封印
    char command[512];
    snprintf(command, sizeof(command), "./audit-seal %s", log_path);
    system(command);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <log-file-path>\n", argv[0]);
        return 1;
    }

    int fd;
    int wd;
    char buffer[EVENT_BUF_LEN];

    // 创建 inotify 实例
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        return 1;
    }

    // 监控文件的修改事件
    wd = inotify_add_watch(fd, argv[1], IN_MODIFY);
    if (wd == -1) {
        perror("inotify_add_watch");
        return 1;
    }

    printf("Watching for changes to %s...\n", argv[1]);

    // 进入循环等待文件变化
    while (1) {
        int length = read(fd, buffer, EVENT_BUF_LEN);
        if (length < 0) {
            perror("read");
        }

        // 处理文件修改事件
        int i = 0;
        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->mask & IN_MODIFY) {
                printf("File %s modified\n", event->name);
                process_log(argv[1]);  // 触发日志处理
            }
            i += EVENT_SIZE + event->len;
        }
    }

    // 关闭 inotify 文件描述符
    close(fd);
    return 0;
}
